package com.smiier.skin.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cn.o.app.event.listener.OnSelectedChangeListener;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OAlert;
import cn.o.app.ui.OAlert.OAlertListener;
import cn.o.app.ui.OBadgeView;
import cn.o.app.ui.OImageView;
import cn.o.app.ui.OTab;
import cn.skinapp.R;

import com.evan.common.adapter.BaseListAdapter;
import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.evan.common.utils.CacheCommon;
import com.lidroid.xutils.BitmapUtils;
import com.smiier.skin.ChatActivity;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.constant.Constant.URL;
import com.smiier.skin.net.AnswerSessionDelTask;
import com.smiier.skin.net.AnswerSessionDelTask.AnswerSessionDelRequest;
import com.smiier.skin.net.AnswerSessionDelTask.AnswerSessionDelResponse;
import com.smiier.skin.net.AnswerSessionGetTask;
import com.smiier.skin.net.AnswerSessionGetTask.AnswerSessionGetRequest;
import com.smiier.skin.net.AnswerSessionGetTask.AnswerSessionGetResponse;
import com.smiier.skin.net.QuestionGetTask;
import com.smiier.skin.net.QuestionGetTask.QuestionGetRequest;
import com.smiier.skin.net.QuestionGetTask.QuestionGetResponse;
import com.smiier.skin.net.RelationshipGetListTask;
import com.smiier.skin.net.RelationshipGetListTask.RelationshipGetListRequest;
import com.smiier.skin.net.RelationshipGetListTask.RelationshipGetListResponse;
import com.smiier.skin.net.entity.QuestionAnswer;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;

/**
 * 1.更改tab变动 才会使adapter数据发生变化 --->参考 adapter的赋值
 * 
 * 
 * 2.添加未读逻辑 operateSessionContent 中 进行数据库的查询，潘盾“readCount”
 * 
 * @author Administrator
 * 
 */

public class SessionFragment extends BasicFragment implements
		OnRefreshListener<ListView>, OnItemClickListener, View.OnClickListener {

	private Button current_btn;

	private PullToRefreshListView list_jiedazhong//, list_yiwancheng
	;

	private SessionAdapter jiedazhongAdapter,yiwanchengAdapter;

	private final int TYPE_JIEDAZHONG = 0, TYPE_YIWANCHENG = 1;

	private int type = TYPE_JIEDAZHONG;

	long start_qid, start_qid_jiedazhong, start_qid_yiwancheng;

	ArrayList<Object> array_jiedazhong = new ArrayList<Object>();
	ArrayList<Object> array_yiwancheng = new ArrayList<Object>();
	TextView text_empty;

	private ImageView img_loading;
	private OTab mTab;
	// 现实这tab 会话上的小气泡

	OBadgeView badge;

	protected View mBadgeTarget;

	private static boolean isNoRead;

	protected boolean mIsRunning = false;

	public SessionFragment(Context context) {
		super(context);
	}

	public SessionFragment(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public SessionFragment(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		this.setContentView(R.layout.fragment_session);
		img_loading = findViewById(R.id.img_loading, ImageView.class);

		init();
		setNavTitle("会话");
		back.setVisibility(View.GONE);
		back.setOnClickListener(this);
		text_right.setOnClickListener(this);

		mTab = findViewById(R.id.tab, OTab.class);
		mTab.setOnSelectedChangeListener(mListener);

		// mTab.setSelectedIndex(1);
		// mTab.setSelectedIndex(0);
		list_jiedazhong = findViewById(R.id.list_jiedazhong,
				PullToRefreshListView.class);
	//	list_yiwancheng = findViewById(R.id.list_yiwancheng,
		//		PullToRefreshListView.class);

		list_jiedazhong.setOnRefreshListener(this);
	//	list_yiwancheng.setOnRefreshListener(this);

		list_jiedazhong.setPullRefreshEnabled(false);
	//	list_yiwancheng.setPullRefreshEnabled(false);

		list_jiedazhong.setScrollLoadEnabled(true);
	//	list_yiwancheng.setScrollLoadEnabled(true);

		list_jiedazhong.setOnItemClickListener(this);
	//	list_yiwancheng.setOnItemClickListener(this);

		text_empty = findViewById(R.id.text_empty, TextView.class);
		jiedazhongAdapter = new SessionAdapter((Activity) getContext(),
				  array_jiedazhong);
		yiwanchengAdapter = new SessionAdapter((Activity) getContext(),
				  array_yiwancheng);
		list_jiedazhong.setAdapter(jiedazhongAdapter);
		/*
		 * jiedazhongAdapter = new SessionAdapter((Activity) getContext(),
		 * array_jiedazhong);
		 * 
		 * list_yiwancheng.setContextEmptyType(false, 1);
		 * list_yiwancheng.setVisibility(View.GONE);
		 * list_jiedazhong.setVisibility(View.VISIBLE); type = TYPE_JIEDAZHONG;
		 * 
		 * 
		 * loadData(false);
		 */

		text_empty.setText("暂无会话");

		list_jiedazhong.getListView().setOnItemLongClickListener(
				new OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> adapterView,
							View view, final int position, long arg3) {
						final JSONObject object = (JSONObject) view.getTag();
						OAlert alert = new OAlert(getContext());
						alert.setOK("确认");
						alert.setCancel("取消");
						alert.setTitle("确认删除当前会话吗？");
						alert.show();
						alert.setListener(new OAlertListener() {

							@Override
							public boolean onOK(OAlert alert) {
								AnswerSessionDelRequest req = new AnswerSessionDelRequest();
								req.qids = new ArrayList<Long>();
								try {
									req.qids.add((long) object.getInt("Qid"));
								} catch (Exception e) {

								}
								req.token = GlobalSettings.sToken;
								AnswerSessionDelTask task = new AnswerSessionDelTask();
								task.setRequest(req);
								task.addListener(new NetTaskListener<AnswerSessionDelTask.AnswerSessionDelRequest, AnswerSessionDelTask.AnswerSessionDelResponse>() {

									@Override
									public void onException(
											INetTask<AnswerSessionDelRequest, AnswerSessionDelResponse> task,
											Exception e) {

									}

									@Override
									public void onComplete(
											INetTask<AnswerSessionDelRequest, AnswerSessionDelResponse> task,
											AnswerSessionDelResponse response) {
										if (response.ResultCode != 200) {
											return;
										}

									}
								});
								add(task);
								return false;
							}

							@Override
							public boolean onCancel(OAlert alert) {
								return false;
							}
						});
						return false;
					}
				});

		
		  IntentFilter filter = new IntentFilter(Constant.RECIVER_CHAT_LIST);
		  getContext().registerReceiver(receiver, filter);
		 

		/*
		 * IntentFilter noReadFilter = new IntentFilter(
		 * Constant.RECIVER_SESSION_ITEM_NOREAD_COUNT);
		 * getContext().registerReceiver(noReadCountReceiver, noReadFilter);
		 */

		IntentFilter noReadTab = new IntentFilter(
				Constant.RECIVER_SESSION_TAB_NOREAD);
		getContext().registerReceiver(noReadTabReceiver, noReadTab);

		IntentFilter filterRefresh = new IntentFilter(
				Constant.RECIVER_CHAT_FINISH_REFRESH);
		getContext().registerReceiver(refreshReceiver, filterRefresh);

		badge = new OBadgeView(getContext(), mBadgeTarget);

		badge.setBackgroundResource(R.drawable.no_read_point);

		badge.setBadgeMargin(CommonUtility.dip2px(getContext(), 20),
				CommonUtility.dip2px(getContext(), 5));

		badge.setHeight(1);
		badge.setWidth(1);

	//	LoadData();

	}

	private void LoadData() {
		list_jiedazhong.setContextEmptyType(false, 2);
	//	list_jiedazhong.setVisibility(View.GONE);
	//	list_jiedazhong.setVisibility(View.VISIBLE);
		type = TYPE_JIEDAZHONG;

		loadData(false);
	}

	public void setBageViewTarget(View v) {
		mBadgeTarget = v;
	}

	@Override
	public void onStart() {
		super.onStart();
		
	
	}

	@Override
	public void onResume() {
		super.onResume();
		// hideBadge();
		
			if(type ==TYPE_JIEDAZHONG ){
				array_jiedazhong.clear();
				mStartIdJieda = null;
				mStartId = null;
				if(jiedazhongAdapter!=null){
					jiedazhongAdapter.notifyDataSetChanged();
				}
				}else if(type ==TYPE_YIWANCHENG){
					array_yiwancheng.clear();
			mStartIdYiwancheng = null;
			mStartId = null;
					if(yiwanchengAdapter!=null){
						yiwanchengAdapter.notifyDataSetChanged();
					}
				}
			loadData(false);
		
		mIsRunning = true;
		/*
		 * list_yiwancheng.setContextEmptyType(false, 1);
		 * list_yiwancheng.setVisibility(View.GONE);
		 * list_jiedazhong.setVisibility(View.VISIBLE); type = TYPE_JIEDAZHONG;
		 * 
		 * loadData(false); mIsRunning = true;
		 */
	}

	@Override
	public void onPause() {
		super.onPause();
		// hideBadge();
		mIsRunning = false;
	}

	/*
	 * protected void showBadge() { if (!mIsRunning) { badge.show(); } }
	 * 
	 * protected void hideBadge() { badge.hide(); }
	 */

	private OnSelectedChangeListener mListener = new OnSelectedChangeListener() {

		@Override
		public void onChanged(View v, int index) {
			//array_jiedazhong.clear();
	
			if (index == 0) {
				list_jiedazhong.setContextEmptyType(false, 2);
				
				if(!array_yiwancheng.isEmpty()){
					array_yiwancheng.clear();
				}
				
				if(yiwanchengAdapter != null){
					yiwanchengAdapter.notifyUpdate(array_yiwancheng);
				}
				
				
				type = TYPE_JIEDAZHONG;
				array_jiedazhong.clear();
				list_jiedazhong.setAdapter(jiedazhongAdapter);
				jiedazhongAdapter.notifyDataSetChanged();
				mStartIdJieda = null;
				mStartId = mStartIdJieda;
			} else if (index == 1) {
				
				if(!array_jiedazhong.isEmpty()){
					array_jiedazhong.clear();
				}
				
				if(jiedazhongAdapter != null){
				    jiedazhongAdapter.notifyUpdate(array_jiedazhong);
				}
				
				
				array_yiwancheng.clear();
				list_jiedazhong.setContextEmptyType(false, 2);
				type = TYPE_YIWANCHENG;
				list_jiedazhong.setAdapter(yiwanchengAdapter);
				yiwanchengAdapter.notifyDataSetChanged();
				mStartIdYiwancheng = null;
				mStartId = mStartIdYiwancheng;
			}			
			loadData(false);
		}
	};

	@Override
	public void onItemClick(AdapterView<?> adapteView, View view, int position,
			long arg3) {
		// clickPosition = position;
		Long qid = null;
		try {
			if(type == TYPE_JIEDAZHONG){
			qid = ((JSONObject) array_jiedazhong.get(position)).getJSONObject(
					"QuestionSearch").getLong("Qid");
			}else{
				qid = ((JSONObject) array_yiwancheng.get(position)).getJSONObject(
						"QuestionSearch").getLong("Qid");
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
	//	if (mType == 1) {
			// 解答中
			QuestionGetTask task = new QuestionGetTask();
			QuestionGetRequest req = new QuestionGetRequest();
			req.qids = new ArrayList<Long>();
			req.qids.add(qid);
			req.token = GlobalSettings.sToken;
			task.addListener(new NetTaskListener<QuestionGetTask.QuestionGetRequest, QuestionGetTask.QuestionGetResponse>() {

				@Override
				public void onComplete(
						INetTask<QuestionGetRequest, QuestionGetResponse> task,
						QuestionGetResponse response) {
					if (response != null && response.Res.size() > 0) {
						QuestionAnswer answer = response.Res.get(0);

						Intent intent = new Intent(getContext(),
								ChatActivity.class);
						try {
							intent.putExtra(Constant.IDENTITY_KEY, JsonUtil
									.convert(answer).toString());
							startActivity(intent);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}

				@Override
				public void onException(
						INetTask<QuestionGetRequest, QuestionGetResponse> task,
						Exception e) {
					e.printStackTrace();
				}
			});
			task.setRequest(req);
			add(task);
//		} else {
			// 已完成

	//	}
		// JSONObject object = (JSONObject) view.getTag();
		// Intent intent = new Intent(getContext(), ChatActivity.class);
		// intent.putExtra(Constant.IDENTITY_KEY, object.toString());
		// startActivity(intent);
	}

	AnimationDrawable ad;
	int mType;
	Long mStartId;
Long mStartIdJieda=null,mStartIdYiwancheng = null;
	public void loadData(boolean isShowDialog) {
		if (GlobalSettings.sUser == null) {
			return;
		}

		setNavTitle("连接中...");
		img_loading.setVisibility(View.VISIBLE);
		ad = (AnimationDrawable) img_loading.getBackground();
		ad.start();
		RelationshipGetListRequest req = new RelationshipGetListRequest();

		req.token = GlobalSettings.sToken;
		
		Log.i("testtoken", "token:" + GlobalSettings.sToken);

		if (type == TYPE_JIEDAZHONG) {
			req.IS_RSAcceptMSG = RelationshipGetListRequest.SESSIONING;
			mType = RelationshipGetListRequest.SESSIONING;
			mStartId = mStartIdJieda;
		} else {
			req.IS_RSAcceptMSG = RelationshipGetListRequest.SESSIONED;
			mType = RelationshipGetListRequest.SESSIONED;
			mStartId = mStartIdYiwancheng;
		}
		req.RSSource = 2l;
		req.pagesize = GlobalSettings.PAGE_SIZE;
		req.startrsuid = mStartId;
		
		RelationshipGetListTask task = new RelationshipGetListTask();
		task.setRequest(req);
		task.addListener(new NetTaskListener<RelationshipGetListTask.RelationshipGetListRequest, RelationshipGetListTask.RelationshipGetListResponse>() {

			@Override
			public void onComplete(
					INetTask<RelationshipGetListRequest, RelationshipGetListResponse> task,
					RelationshipGetListResponse response) {
				list_jiedazhong.doComplete();
				list_jiedazhong.setVisibility(View.VISIBLE);
				if (response.ResultCode != 200) {
					toast(R.string.server_unavailable);
					list_jiedazhong.setContextEmptyType(true, 2);
		//			list_yiwancheng.setContextEmptyType(true, 2);
					return;
				}

				try {
					JSONArray arr = new JSONArray(JsonUtil
							.convert(response.Res.Users));
					
					Log.i("testwancheng", "load.arr");
					
					list_jiedazhong.setContextEmptyType(false, 2);
			//		list_yiwancheng.setContextEmptyType(false, 2);
					
					if(ad != null && img_loading != null){
						ad.stop();
						ad = null;
						img_loading.setVisibility(View.GONE);
						setNavTitle("会话");
					}
					
					Log.i("testwancheng", "ad");
					

					if (type == TYPE_JIEDAZHONG) {

						if (arr.length() > 0) {

							operateSessionContent(arr, array_jiedazhong,
									list_jiedazhong/* , jiedazhongAdapter */);
							
							if(jiedazhongAdapter == null){
								jiedazhongAdapter = new SessionAdapter((Activity)getContext(), array_jiedazhong);
							}

							list_jiedazhong.setAdapter(jiedazhongAdapter);
							
							jiedazhongAdapter.notifyDataSetChanged();
						} else {
							if (list_jiedazhong.getListView().getChildCount() < 2) {
								list_jiedazhong.setContextEmptyType(true, 2);
							} else {
								list_jiedazhong.setContextEmptyType(false, 2);
							}
						}
					} else if (type == TYPE_YIWANCHENG) {
						
						Log.i("testwancheng", "arr.length:" + arr.length());
						
						if (arr.length() > 0) {
							
								operateSessionContent(arr, array_yiwancheng,
										list_jiedazhong);			
								
								
								if(yiwanchengAdapter == null){
									yiwanchengAdapter = new SessionAdapter((Activity)getContext(), array_yiwancheng);
								}
								
								list_jiedazhong.setAdapter(yiwanchengAdapter);
								
								
							  yiwanchengAdapter.notifyDataSetChanged();

						} else {

							if (array_yiwancheng.size() > 0) {
								list_jiedazhong.setHasMoreData(false);
							}
							/*ad.stop();
							ad = null;
							img_loading.setVisibility(View.GONE);
							setNavTitle("会话");*/

							if (list_jiedazhong.getListView().getChildCount() < 2) {
								list_jiedazhong.setContextEmptyType(true, 2);
							} else {
								list_jiedazhong.setContextEmptyType(false, 2);
							}
						}
					}

				} catch (Exception e) {

					Log.i("testwancheng", "load.exception" + e.toString());

				}
			}

			@Override
			public void onException(
					INetTask<RelationshipGetListRequest, RelationshipGetListResponse> task,
					Exception e) {
				list_jiedazhong.doComplete();
				e.printStackTrace();
			}
		});

		add(task);

	}

	int unReadNum = 0;

	void operateSessionContent(final JSONArray src,
			final ArrayList<Object> dest, final PullToRefreshListView listview) {
		Intent refreshIntent = new Intent(Constant.RECIVER_SESSION_TAB_NOREAD);
		refreshIntent.putExtra("show", true);
		getContext().sendBroadcast(refreshIntent);

		// 先显示问题
		try {
			for (int i = 0; i < src.length(); i++) {
				JSONArray session_value = new JSONArray();
				JSONObject ooo = src.getJSONObject(i);
				JSONObject oooo = new JSONObject();
				if (type == TYPE_JIEDAZHONG) {
					oooo.put("Content",
							ooo.getJSONObject("User").getString("Name")
									+ "给你发起会话");
				} else {
					oooo.put("Content", "会话问诊已结束");
				}
				oooo.put("CreateTime", "");
				oooo.put("FilePath", "");
				oooo.put("FileLength", "");
				oooo.put("Pic", new JSONArray());
				session_value.put(oooo);
				ooo.put("session_record", session_value);

				// ooo.put("unReadNum", 0);
				if(ooo.has("QuestionSearch")){
					String uid = ooo.getJSONObject("QuestionSearch").getString(
							"Doctor_Uid");

					ooo.put("unReadNum", getNoReadCount(uid));
				}
			}
			CommonUtility.putAll(dest, src, true);
			/*if (array_jiedazhong.size() > 0) {
				
				mStartId = ((JSONObject) array_jiedazhong.get(array_jiedazhong
						.size() - 1)).getJSONObject("User").getLong("Uid");
			}*/

			if (dest.size() > 0) {
				if (type == TYPE_JIEDAZHONG) {
					mStartIdJieda = ((JSONObject) dest
							.get(array_jiedazhong.size() - 1)).getLong("Uid");
				} else {
					mStartIdYiwancheng = ((JSONObject) dest
							.get(array_yiwancheng.size() - 1)).getLong("Uid");
				}
				text_empty.setVisibility(View.GONE);
			} else {
				text_empty.setVisibility(View.VISIBLE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (type == TYPE_YIWANCHENG) {
			if (!CommonUtility.isNull(ad)) {
				ad.stop();
				ad = null;
			}
			img_loading.setVisibility(View.GONE);
			setNavTitle("会话");
			return;
		}

		AnswerSessionGetRequest req = new AnswerSessionGetRequest();
		req.pagesize = 1;
		req.token = GlobalSettings.sToken;
		req.Is_New = GlobalSettings.IS_FALSE;
		req.qids = new ArrayList<Long>();
		for (int i = 0; i < dest.size(); i++) {
			try {
				req.qids.add((long) ((JSONObject) dest.get(i)).getInt("Qid"));
			} catch (Exception e) {

			}
		}
		if (req.qids.size() == 0) {
			req.qids = null;
		}

		if (type == TYPE_JIEDAZHONG) {
			AnswerSessionGetTask task = new AnswerSessionGetTask();
			task.setRequest(req);
			task.addListener(new NetTaskListener<AnswerSessionGetTask.AnswerSessionGetRequest, AnswerSessionGetTask.AnswerSessionGetResponse>() {

				@Override
				public void onException(
						INetTask<AnswerSessionGetRequest, AnswerSessionGetResponse> task,
						Exception e) {
					listview.doComplete();
					if (!CommonUtility.isNull(ad)) {
						ad.stop();
						ad = null;
					}
					img_loading.setVisibility(View.GONE);
					setNavTitle("会话");
				}

				@Override
				public void onComplete(
						INetTask<AnswerSessionGetRequest, AnswerSessionGetResponse> task,
						AnswerSessionGetResponse response) {
					listview.doComplete();
					if (!CommonUtility.isNull(ad)) {
						ad.stop();
						ad = null;
					}
					img_loading.setVisibility(View.GONE);
					setNavTitle("会话");
					if (response.ResultCode != 200) {
						return;
					}
					try {
						JSONArray array_session = new JSONArray(JsonUtil
								.convert(response.Res.Session));
						int length = dest.size();
						for (int i = 0; i < length; i++) {
							JSONObject destObject = (JSONObject) dest.get(i);
							for (int j = 0; j < array_session.length(); j++) {
								if (destObject.getInt("Qid") == array_session
										.getJSONObject(i).getInt("Key")) {
									JSONArray session_value = array_session
											.getJSONObject(i).getJSONArray(
													"Value");
									JSONObject ooo = (JSONObject) dest.get(i);
									if (session_value.length() < 1) {
										JSONObject oooo = new JSONObject();
										oooo.put(
												"Content",
												ooo.getJSONObject("Doctor_User")
														.getString("Name")
														+ "给你发起会话");
										oooo.put("CreateTime", "");
										oooo.put("FilePath", "");
										oooo.put("FileLength", "");
										oooo.put("Pic", new JSONArray());
										session_value.put(oooo);
									}
									ooo.put("session_record", session_value);
									break;
								}
							}
						}
					} catch (Exception e) {
						System.err.println(e);
					}
					try {
						JSONArray array = new JSONArray(JsonUtil
								.convert(response.Res.UnRead));
						int length = array.length();
						int destSize = dest.size();
						unReadNum = array.length();
						unReadNum = 0;
						for (int i = 0; i < length; i++) {
							unReadNum += array.getJSONObject(i).getInt("Value");
							for (int j = 0; j < destSize; j++) {
								JSONObject destObject = (JSONObject) dest
										.get(j);
								JSONObject unreadObject = array
										.getJSONObject(i);
								if (destObject.getInt("Qid") == unreadObject
										.getInt("Key")) {
									destObject.put("unReadNum",
											unreadObject.getInt("Value"));
									break;
								}
							}
						}
					} catch (Exception e) {
						System.err.println(e);
					}
				}
			});
			add(task);
		}
	}

	private int getNoReadCount(String uid) {

		int noRead = 0;

		ArrayList<CacheCommon> caches = dbUtil.queryCache(
				ChatActivity.class.getSimpleName(), uid);

		ArrayList<Object> recordArray = new ArrayList<Object>();

		if (caches.size() > 0) {
			String datas = caches.get(0).data;
			try {
				JSONArray arrays = new JSONArray(datas);
				CommonUtility.putAll(recordArray, arrays, true);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (!recordArray.isEmpty()) {
			for (Object object : recordArray) {
				try {
					JSONObject item = new JSONObject(object.toString());

					if (!item.getBoolean("readState")) {
						noRead++;
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return noRead;
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

	}

	@Override
	public void onPullUpToLoadMore(PullToRefreshBase<ListView> refreshView) {
		loadData(false);
	}
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if(type ==TYPE_JIEDAZHONG ){
			array_jiedazhong.clear();
			mStartIdJieda = null;
			mStartId = null;
			if(jiedazhongAdapter!=null){
				jiedazhongAdapter.notifyDataSetChanged();
			}
			}else if(type ==TYPE_YIWANCHENG){
				array_yiwancheng.clear();
		mStartIdYiwancheng = null;
		mStartId = null;
				if(yiwanchengAdapter!=null){
					yiwanchengAdapter.notifyDataSetChanged();
				}
			}
			loadData(false);
		}
	};
	BroadcastReceiver refreshReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				if (GlobalSettings.sUser == null) {
					return;
				}
				JSONObject newData = new JSONObject(
						intent.getStringExtra(Constant.IDENTITY_KEY));
				JSONObject o = null;
				int size = array_jiedazhong.size();
				for (int i = 0; i < size; i++) {
					o = (JSONObject) array_jiedazhong.get(i);
					if (o.getInt("Qid") == newData.getInt("Qid")) {
						array_jiedazhong.remove(i);
						array_jiedazhong.add(i, newData);

					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	/**
	 * 因为 广播 参数不熟 自己写
	 * 
	 */

	BroadcastReceiver noReadTabReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				if (GlobalSettings.sUser == null) {
					return;
				}
				
				
				if(jiedazhongAdapter != null){
					jiedazhongAdapter.notifyDataSetChanged();
				}
				
				String intentUid = intent.getStringExtra("uid");

				ArrayList<String> uids = new ArrayList<String>();

				if (intentUid != null) {
					if (array_jiedazhong != null && !array_jiedazhong.isEmpty()) {
							/*uids.add(((JSONObject) item).getJSONObject(
									"QuestionSearch").getString("Doctor_Uid"));*/
						
						Log.i("testdoctordata", "array_jiedazhong.size:" + array_jiedazhong.size());
						
						
						for(int i = 0; i < array_jiedazhong.size(); i++){
							
							String uid = new JSONObject(array_jiedazhong.get(i).toString()).getJSONObject("QuestionSearch").getString("Uid");
							
							Log.i("testdoctordata", "uid:");
						}
					}
				/*	if (!uids.contains(intentUid)) {
						array_jiedazhong.clear();
						mStartId = null
								;
						if(jiedazhongAdapter!=null){
							jiedazhongAdapter.notifyDataSetChanged();
						}
						loadData(false);
					}*/
				}

				if (GlobalSettings.appStart) {
					Intent refreshIntent = new Intent(
							Constant.RECIVER_SESSION_TAB_NOREAD);
					getContext().sendBroadcast(refreshIntent);
					GlobalSettings.appStart = false;
				}

				JSONObject itemo = null;
				int itemSize = array_jiedazhong.size();
				
				Log.i("testreceiverpoint", "itemSize:" + itemSize);
				
				
				for (int i = 0; i < itemSize; i++) {
					itemo = (JSONObject) array_jiedazhong.get(i);

					String uid = itemo.getJSONObject("QuestionSearch")
							.getString("Uid") + "";
					itemo.put("unReadNum", getNoReadCount(uid));

					if (jiedazhongAdapter != null) {
						jiedazhongAdapter.notifyDataSetChanged();
					}
				}
				int size = array_jiedazhong.size();
				int num = 0;
				if (size > 0) {
					for (Object item : array_jiedazhong) {
						JSONObject o = (JSONObject) item;
						try {
							String uid = o.getJSONObject("QuestionSearch")
									.getString("Uid") + "";
							num = num + getNoReadCount(uid);

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}
				Log.i("testreceiverpoint", "num:" + num);
				
				if (num > 0) {
					isNoRead = true;
				} else {
					isNoRead = false;
				}

				myHandler.sendEmptyMessage(0);
			} catch (Exception e) {
				e.printStackTrace();
				
			}

		}
	};

	/*
	 * BroadcastReceiver noReadCountReceiver = new BroadcastReceiver() {
	 * 
	 * @Override public void onReceive(Context context, Intent intent) { try {
	 * if (GlobalSettings.sUser == null) { return; }
	 * 
	 * String qid = intent.getStringExtra("qid"); JSONObject o = null; int size
	 * = array_jiedazhong.size(); for (int i = 0; i < size; i++) { o =
	 * (JSONObject) array_jiedazhong.get(i);
	 * 
	 * if (o.getJSONObject("QuestionSearch").getInt("Qid") == Integer
	 * .valueOf(qid)) {
	 * 
	 * JSONObject object = (JSONObject) array_jiedazhong .get(i);
	 * object.put("unReadNum", 0); array_jiedazhong.remove(i);
	 * array_jiedazhong.add(object); }
	 * 
	 * if (jiedazhongAdapter != null) {
	 * jiedazhongAdapter.notifyUpdate(array_jiedazhong);
	 * jiedazhongAdapter.notifyDataSetChanged(); }
	 * 
	 * Intent refreshIntent = new Intent( Constant.RECIVER_SESSION_TAB_NOREAD);
	 * refreshIntent.putExtra("show", true);
	 * getContext().sendBroadcast(refreshIntent);
	 * 
	 * } } catch (Exception e) { e.printStackTrace(); }
	 * 
	 * } };
	 */

	// private int clickPosition = 0;
	/*
	 * BroadcastReceiver receiver = new BroadcastReceiver() {
	 * 
	 * @Override public void onReceive(Context context, Intent intent) { try {
	 * if (GlobalSettings.sUser == null) { return; } mTab.setSelectedIndex(0);
	 * if (type == TYPE_JIEDAZHONG) {
	 * 
	 * start_qid_jiedazhong = 0; array_jiedazhong.clear(); loadData(false); } }
	 * catch (Exception e) { e.printStackTrace(); } } };
	 */

	public void onDestroy() {
		super.onDestroy();
		// CommonUtility.unRegisteReciver((Activity) getContext(), receiver);

		CommonUtility.unRegisteReciver((Activity) getContext(),
				noReadTabReceiver);

		/*
		 * CommonUtility.unRegisteReciver((Activity) getContext(),
		 * noReadCountReceiver);
		 */
		CommonUtility
				.unRegisteReciver((Activity) getContext(), refreshReceiver);

		isNoRead = false;

	}

	public class SessionAdapter extends BaseListAdapter {

		/**
		 * @param activity
		 * @param array
		 */
		BitmapUtils mBitmapUtils;

		public SessionAdapter(Activity activity, ArrayList<Object> array) {
			super(activity, array);
			mBitmapUtils = new BitmapUtils(activity);
		}

		class ViewHolder {
			TextView text_doctor_name, text_chat_name, text_chat_content,
					text_date, not_check_count,text_hospital_name;
			OImageView img;
			ImageView img_chat_status;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder viewHolder = null;
			if (CommonUtility.isNull(convertView)) {
				convertView = inflater.inflate(R.layout.item_session, null);
				viewHolder = new ViewHolder();
				viewHolder.img = (OImageView) convertView
						.findViewById(R.id.imgLayout_show);
				viewHolder.img_chat_status = (ImageView) convertView
						.findViewById(R.id.img_chat_status);
				viewHolder.text_doctor_name = (TextView) convertView
						.findViewById(R.id.text_doctor_name);
				viewHolder.text_chat_content = (TextView) convertView
						.findViewById(R.id.text_chat_content);
				viewHolder.text_hospital_name = (TextView) convertView.findViewById(R.id.text_hospital_name);
				viewHolder.text_date = (TextView) convertView
						.findViewById(R.id.text_date);
				viewHolder.not_check_count = (TextView) convertView
						.findViewById(R.id.not_check_count);
				/*
				 * BadgeView badgeView = new BadgeView(activity,
				 * viewHolder.img);
				 * badgeView.setBackgroundResource(R.drawable.badge_ifaux);
				 * badgeView.setGravity(Gravity.CENTER);
				 * badgeView.setTextSize(13);
				 * viewHolder.img.setTag(R.id.tag_obj1, badgeView);
				 */
				CommonUtility.setViewHolderTag(convertView, viewHolder);
			} else {
				viewHolder = (ViewHolder) CommonUtility
						.getViewHolderTag(convertView);
			}

			JSONObject object = (JSONObject) getItem(position);

			try {
				
				int status = 0;
				
				if(object.has("QuestionSearch")){
					 status = object.getJSONObject("QuestionSearch").getInt(
							"Status");
					if (status == 3) {
						viewHolder.img_chat_status
								.setBackgroundResource(R.drawable.chat_status_finish);
					} else {
						viewHolder.img_chat_status
								.setBackgroundResource(R.drawable.chat_status_no_finish);
					}
				}else{
					viewHolder.img_chat_status
					.setBackgroundResource(R.drawable.chat_status_finish);
				}
				
				
				
				JSONObject doctor = object.getJSONObject("User");
				JSONObject patient = object.getJSONObject("QuestionSearch");
				String iconPath = null;
				if (// CommonUtility.isDoctor()
				true) {
					iconPath = doctor.getString("Pic");
					viewHolder.text_doctor_name.setText(doctor
							.getString("Name"));
				} else {
					iconPath = doctor.getString("Pic");
					viewHolder.text_doctor_name.setText(doctor
							.getString("Name")
							+ "（"
							+ doctor.getString("Hospital") + "）");
				}
				
				initChatContent(doctor.getString("Uid"),viewHolder.text_chat_content,viewHolder.text_date,status);
				
				
				/*JSONArray recordArray = object.getJSONArray("session_record");
				if (recordArray.length() > 0) {
					JSONObject record = recordArray.getJSONObject(recordArray
							.length() - 1);
					try {
						String content = record.getString("Content");
						if (!CommonUtility.isNull(content)) {
							int is_appraise = object.getJSONObject(
									"QuestionSearch").getInt("Is_Appraise");
							// 医生已下诊断但还未评价
							if (status == 3 && is_appraise == 0) {
								content = "医生解答完成，待评价";
							}
							viewHolder.text_chat_content.setText(content);
						}
					} catch (Exception e) {
						// TODO: handle exception
					}
					try {
						String voicePath = record.getString("FilePath");
						if (!CommonUtility.isNull(voicePath)) {
							viewHolder.text_chat_content.setText("/语音/");
						}
					} catch (Exception e) {
						// TODO: handle exception
					}
					try {
						int picLength = record.getJSONArray("Pic").length();
						if (picLength > 0) {
							viewHolder.text_chat_content.setText("/图片/");
						}
					} catch (Exception e) {
						// TODO: handle exception
					}
					viewHolder.text_date.setText(CommonUtility.formatDate(
							record.getString("CreateTime"), 0, 10));
				} else {
					viewHolder.text_chat_content.setText(null);
					viewHolder.text_date.setText(null);
				}*/
				
				
				
				
				String unread = object.getString("unReadNum");
				if (Integer.valueOf(unread) > 0) {
					viewHolder.not_check_count.setVisibility(View.VISIBLE);
					viewHolder.not_check_count.setText(unread + "");
				} else {
					viewHolder.not_check_count.setVisibility(View.GONE);
				}

				final String icon = iconPath;
				CommonUtility.setImageIdentityTag(viewHolder.img, iconPath);
				CommonUtility.displayHeadImage(viewHolder.img, mBitmapUtils,
						GlobalSettings.SERVER_IMG_URL + iconPath
								+ GlobalSettings.IMG_SRC, getResources(),
						doctor.getInt("Sex"));
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			convertView.setTag(object);
			// CommonUtility.setListViewItemBG(convertView, position);
			return convertView;
		}

	}

	@Override
	public void onClick(View v) {

	}

	public void initChatContent(String uid, TextView text_chat_content,
			TextView text_date, int status) {
		
		
		Log.i("testxxx", ".....");
		
		ArrayList<CacheCommon> caches = dbUtil.queryCache("ChatActivity", uid);
		ArrayList<Object> recordArray = new ArrayList<Object>();
		if (caches.size() > 0) {
			String data = caches.get(0).data;
			try {
				JSONArray array = new JSONArray(data);
				CommonUtility.putAll(recordArray, array, true);
				
				JSONObject item = new JSONObject(recordArray.get(0).toString());
				
				String content = new String();
				
				
				if(item.has("Content")){
					if(item.getString("Content").contains("jpg")){
						content = "[ 图片 ]";
						
						Log.i("testxxx", "jpg:");
						
					}else{
						
						Log.i("testxxx", "content:");
						content = item.getString("Content");
					}
				}
				
			  if(content.isEmpty()){
				  content = "[ 语音 ]";
			  }
				
				
				text_date.setText(item.getString("CreateTime"));
				text_chat_content.setText(content);
				
				
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}else{
			text_date.setVisibility(View.INVISIBLE);
			text_chat_content.setText("暂无历史记录");
		}
		
		
		
		
	}

	Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				if (isNoRead) {
					badge.show();
				} else {
					badge.hide();
				}

				break;
			}
		}
	};

}
